﻿using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using SQLToolbox.Controller.Tools;
using SQLToolbox.Controller;
using SQLToolbox.View.Types;
using SQLToolbox.Types;

namespace SQLToolbox.View.UserControls
{
	/// <summary>
	/// Interaction logic for ucDBConnection.xaml
	/// </summary>
	public partial class ucDBConnection : UserControl
	{
		private bool providerChanged = false;
		DBConnector connector;

		public ucDBConnection(DBConnector conn, string name)
		{
			this.Name = name;
			InitializeComponent();
			connector = conn;
			cmbDatasource.ItemsSource = connector.AvailableDataSources;
			cmbDatasource.SelectedIndex = 0;
			cmbDatasource.IsEnabled = false;
			rbIntegrated.GroupName = string.Format("{0}_{1}", this.Name, rbIntegrated.GroupName);
			rbSQL.GroupName = string.Format("{0}_{1}", this.Name, rbSQL.GroupName);
		}


		public ucDBConnection()
		{
			InitializeComponent();
		}


		private void comboBox2_DropDownOpened(object sender, EventArgs e)
		{
			if (providerChanged)
			{
				Cursor ct = this.Cursor;
				this.Cursor = Cursors.Wait;
				cmbServer.ItemsSource = connector.GetServers(cmbDatasource.Text);
				providerChanged = false;
				this.Cursor = ct;
			}
		}

		private void cmbDatasources_SelectionChanged(object sender, SelectionChangedEventArgs e)
		{
			providerChanged = true;
		}


		private void btnTestConnection_Click(object sender, RoutedEventArgs e)
		{
			bool success = Validate();

			if (success)
				MessageBox.Show("Connection Successeded");
			else
				MessageBox.Show("Connection failed");
		}

		private void Authentication_Checked(object sender, RoutedEventArgs e)
		{
			if (rbIntegrated.IsChecked == true)
			{
				txtUname.IsEnabled = false;
				txtPassword.IsEnabled = false;
			}
			else
			{
				txtUname.IsEnabled = true;
				txtPassword.IsEnabled = true;
			}
		}

		private void cmbDatabase_DropDownOpened(object sender, EventArgs e)
		{

			Cursor ct = this.Cursor;
			this.Cursor = Cursors.Wait;
			try
			{
				cmbDatabase.ItemsSource = connector.GetDatabases(new DBConnectionProperties { DataSource = cmbDatasource.Text, ServerName = cmbServer.Text, Credentials = CreateCredentials() });
			}
			catch (SQLToolboxControllerException ex)
			{
				MessageBox.Show(ex.Message, "Could not retrieve database list", MessageBoxButton.OK, MessageBoxImage.Error);
			}
			this.Cursor = ct;
		}


		public bool Validate()
		{
			if ((!string.IsNullOrEmpty(cmbServer.Text)) &&
				(connector.TryToConnect(new DBConnectionProperties { DataSource = cmbDatasource.Text, ServerName = cmbServer.Text, Credentials = CreateCredentials(), DatabaseName = cmbDatabase.Text }) == true))
				return true;
			return false;
		}
		ConnectionCredentials CreateCredentials()
		{
			ConnectionCredentials cc = new ConnectionCredentials { IntegratedSecurity = true };
			if (rbIntegrated.IsChecked == false)
			{
				cc.Username = txtUname.Text;
				cc.Password = txtPassword.Password;
				cc.IntegratedSecurity = false;
			}
			return cc;
		}

		public string DataSource
		{
			get { return cmbDatasource.Text; }
			set { cmbDatasource.Text = value; }
		}
		public string Server
		{
			get { return cmbServer.Text; }
			set { cmbServer.Text = value; }
		}
		public ConnectionCredentials Credentials
		{
			get { return CreateCredentials(); }
			set
			{
				txtUname.Text = value.Username;
				txtPassword.Password = value.Password;
				rbIntegrated.IsChecked = value.IntegratedSecurity;
				rbSQL.IsChecked = !value.IntegratedSecurity;
			}
		}
		public string Database
		{
			get { return cmbDatabase.Text; }
			set
			{
				if (cmbDatabase.Items.Contains(value))
				{
					cmbDatabase.SelectedValue = value;
				}
			}
		}
		[DialogValue]
		public DBConnectionProperties Value
		{
			get
			{
				return new DBConnectionProperties { DataSource = string.Copy(DataSource), ServerName = string.Copy(Server), Credentials = CreateCredentials(), DatabaseName = string.Copy(Database) };
			}
		}

		[DialogButton("OK")]//, Number = 0)]
		public bool? OkClicked()
		{
			if (Validate())
				return true;
			else
				MessageBox.Show("Could not connect to databases for comparison", "Connection error",
					MessageBoxButton.OK, MessageBoxImage.Error);
			return null;

		}

		[DialogButton("Cancel")]//, Number = 1)]
		public bool? CancelClicked()
		{
			return false;
		}

		public string Title
		{
			get { return "Connect to database"; }
		}
	}
}

